package com.loveyukari.utils;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import org.apache.commons.net.util.Base64;

/**
*
*yangshaohua
*2017年10月16日上午10:38:57
**/
public class AESUtils {
	
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @param password 加密密码
     * @return 返回Base64转码后的加密数据
     * @throws Exception 
     */
    public static String encrypt(String content, String password) throws Exception {
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器
        byte[] result = cipher.doFinal(content.getBytes("utf-8"));// 加密
        return Base64.encodeBase64String(result);//通过Base64转码返回
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @param password
     * @return
     * @throws Exception 
     */
    public static String decrypt(String content, String password) throws Exception {
		Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
		byte[] result = cipher.doFinal(Base64.decodeBase64(content));
		return new String(result, "utf-8");
    }

    /**
     * 生成加密秘钥
     *
     * @return
     * @throws NoSuchAlgorithmException 
     */
    private static SecretKey getSecretKey(final String password) throws NoSuchAlgorithmException {
         KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);  
         SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");  
         secureRandom.setSeed(password.getBytes());  
         // AES加密数据块分组长度必须为128比特，密钥长度可以是128比特、192比特、256比特中的任意一个  
         kgen.init(128, secureRandom);  
         SecretKey secretKey = kgen.generateKey();  
         return secretKey;
    //返回生成指定算法密钥生成器的 KeyGenerator 对象
    }
}
